package com.example.testservicce;



import android.Manifest;
import android.annotation.SuppressLint;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.ServiceConnection;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaMetadataRetriever;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Environment;

import android.os.IBinder;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;


import com.example.testservicce.service.MusicPlayService;
import com.example.testservicce.service.MyBindService;
import com.example.testservicce.utils.MusicPlayUtils;

import java.io.File;

import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;

import pub.devrel.easypermissions.EasyPermissions;


public class MusicActivity extends AppCompatActivity {
   ArrayList<File> songFiles;
    File[]filesongs;
    ArrayList<String >info=new ArrayList<>();
    MusicPlayService.MusicAgency ma;
    private MyConn conn;

    class MyConn implements ServiceConnection{

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            ma= (MusicPlayService.MusicAgency) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {


        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_music);
        String[]perms={Manifest.permission.READ_EXTERNAL_STORAGE };
        if(!EasyPermissions.hasPermissions(this,perms)){
            EasyPermissions.requestPermissions(this,"request read storage",1,perms);
        }
        ListView lvMusic= (ListView) findViewById(R.id.lv_music);

        //getMusicFiles();
        getPhoneMusic();
        //getInfo();
        Intent intent=new Intent(this,MusicPlayService.class);
        conn = new MyConn();
        bindService(intent, conn,BIND_AUTO_CREATE);

        lvMusic.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return songFiles.size();
                //return filesongs.length;
            }

            @Override
            public Object getItem(int position) {
                return null;
            }

            @Override
            public long getItemId(int position) {
                return 0;
            }

            @Override
            public View getView(final int position, View convertView, ViewGroup parent) {
                View view=View.inflate(getApplicationContext(),R.layout.music_item,null);
                TextView title= (TextView) view.findViewById(R.id.tv_title);
                Button start= (Button) view.findViewById(R.id.btn_start);
                Button stop= (Button) view.findViewById(R.id.btn_stop);
                title.setText(((File)songFiles.get(position)).getName());
                //title.setText(filesongs[position].getName());
                //title.setText(getSongInfo(filesongs[position]));
                start.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //MusicPlayUtils.startPlay(songFiles.get(position).getPath());
                        //if (ma!=null){
                            ma.paly(songFiles.get(position).getPath());
                        //}

                    }
                });
                stop.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                       // MusicPlayUtils.stopPlay();
                        //if (ma!=null){
                            ma.stop();
                        //}
                    }
                });
//                start.setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        MediaPlayer mp=new MediaPlayer();
//                        mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
//                        try {
//                            mp.setDataSource(songFiles.get(position).getPath());
//                            mp.prepare();//耗时操作
//                            mp.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
//                                @Override
//                                public void onPrepared(MediaPlayer mp) {
//                                    mp.start();
//                                }
//                            });
//                        } catch (IOException e) {
//                            e.printStackTrace();
//                        }
//
//                    }
//                });
                return view;
            }
        });
    }

    private void getPhoneMusic() {
        //获取系统提供的媒体数据库中的音乐媒体数据
        //内容提供者---系统---提供的资源地址Uri
        //内容解析者---程序--根据Uri获取
        Uri uriSD= MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
        Uri uriMem=MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
        //查询sd卡中的音乐数据
        ContentResolver resolver = getContentResolver();
        //参数1-uri
        //参数2-目标列
        //参数3-查询条件
        //参数4-占位符
        //参数5查询结果排序

        Cursor cursor = resolver.query(uriSD, null, null, null, null);
        songFiles=new ArrayList<>();
        while(cursor.moveToNext()){
            String path=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
            File file=new File(path);
            Log.i("Main", "getPhoneMusic: "+path);
            songFiles.add(file);

        }
        //mem

         cursor = resolver.query(uriMem, null, null, null, null);

        while(cursor.moveToNext()){
            String path=cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA));
            File file=new File(path);
            songFiles.add(file);

        }
        cursor.close();


    }

//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        unbindService(conn);
//    }

    private void getInfo() {
        //使用MediaMetadataRetriever获取mp3文件的信息
        //
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        String str = Environment.getExternalStorageDirectory() + "/music/思凡.mp3";
        String TAG="MainMusic";
        Log.d(TAG, "str:" + str);
        try {
            mmr.setDataSource(str);
            String title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE); // api level 10, 即从GB2.3.3开始有此功能
            Log.d(TAG, "title:" + title);
            String album = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ALBUM);
            Log.d(TAG, "album:" + album);
            String mime = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
            Log.d(TAG, "mime:" + mime);
            String artist = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);
            Log.d(TAG, "artist:" + artist);
            String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION); // 播放时长单位为毫秒
            Log.d(TAG, "duration:" + duration);
            String bitrate = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_BITRATE); // 从api level 14才有，即从ICS4.0才有此功能
            Log.d(TAG, "bitrate:" +bitrate);
            String date = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DATE);
            Log.d(TAG, "date:" + date);
        } catch (IllegalArgumentException e) {			// TODO Auto-generated catch block
             		e.printStackTrace();
        } catch (IllegalStateException e) {			// TODO Auto-generated catch block
             		e.printStackTrace();
        }
    }

    private String  getSongInfo(File f) {
        String songName="";

        byte[]info=new byte[128];
        try {
            FileInputStream fis=new FileInputStream(f);
            int offset=fis.available()-128;
            if(offset<0){
                songName="error";
                return songName;
            }
            fis.skip(offset);
            int len=fis.read(info);
            String tag=new String(info,0,3);
            if(tag.equals("TAG")){
                songName=new String(info,3,30,"gbk").trim();


            }
            Log.i("Info", "getSongInfo: "+new String(info,"gbk"));
            fis.close();
            return songName;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }


        return songName;
    }


    private void getMusicFiles() {
       String path= Environment.getExternalStorageDirectory()+"/music";
        Log.i("Main", "getMusicFiles: "+path);

        File dir=new File(path);
        File[]files=dir.listFiles();
        String songName="";
        MediaMetadataRetriever mmr=new MediaMetadataRetriever();
        songFiles=new ArrayList<File>();
        for (File f:files
             ) {
            if (f.getName().endsWith(".mp3")){
                songFiles.add(f);
                Log.i("Main", "getSongInfo: "+ f.getAbsolutePath() );
                FileInputStream inputStream = null;
                try {
                    inputStream = new FileInputStream(f);
                    mmr.setDataSource(inputStream.getFD());
                    //mmr.setDataSource( f.getPath(),new HashMap<String, String>());
                    songName=mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
                    info.add(songName);
                    Log.i("Main", "title: "+ songName);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }



            }



        }


        mmr.release();
        filesongs=dir.listFiles(new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                if (pathname.getName().endsWith(".mp3")){
                    return  true;
                }
                return false;
            }
        });

        Log.i("Main", "length: "+songFiles.size());


//        songFiles.removeIf(new Predicate<File>() {
//            @Override
//            public boolean test(File file) {
//                if (file.getName().endsWith(".mp3")){
//                    return  false;
//                }
//                return true;
//            }
//        });

        Log.i("Main", "length: "+songFiles.size());


    }
}
